using Markdig;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Text.RegularExpressions;
using System.Web;

namespace DocumentGen
{

    public class TitleData
    {
        /// <summary>
        /// 标题等级（如：h1,h2,h3）
        /// </summary>
        public int level { get; set; }
        /// <summary>
        /// 页面的偏移量，用于构造锚点name值
        /// </summary>
        public int offset { get; set; }
    }
    public class IF_MarkDown
    {
        /// <summary>
        /// 获取MD文档的正文的context标题
        /// </summary>
        /// <returns></returns>
        public static Dictionary<TitleData, string> GetContextTitle(string context)
        {
            Dictionary<TitleData, string> title_list = new Dictionary<TitleData, string>();
            string[] str_line = context.Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
            int line = 1;
            Dictionary<int, int> label_count = new Dictionary<int, int>();
            label_count.Add(1, 1); //<h1>
            label_count.Add(2, 1);
            label_count.Add(3, 1);
            label_count.Add(4, 1);
            label_count.Add(5, 1);
            label_count.Add(6, 1);

            foreach (var item in str_line)
            {
                
                if (item.StartsWith("#") && !item.StartsWith("#include")&&!item.StartsWith("#ifndef") &&!item.StartsWith("#define") && !item.StartsWith("#endif"))
                {
                    int index = item.IndexOf(' ');
                    TitleData data = new TitleData();
                    data.level = index;
                    //data.offset = line++;
                    data.offset = label_count[index]++;
                    title_list.Add(data, item.Substring(index).Trim());
                }
            }
            return title_list;
        }

        private static string InsertHoverLabel(string html, string label)
        {
            //string label = "<h2>";
            int index = html.IndexOf(label);
            int count = 1;
            int level = 1;
            switch (label)
            {
                case "<h1>": level = 1; break;
                case "<h2>": level = 2; break;
                case "<h3>": level = 3; break;
                case "<h4>": level = 4; break;
                case "<h5>": level = 5; break;
                case "<h6>": level = 6; break;
                default: level = 0; break;
            }
            while (index >= 0)
            {
                html = html.Insert(index + 3, $" id='title_L{level}_{count++}' ");
                index = html.IndexOf(label);
            }
            return html;
        }
        public static string SetImageCenter(string html)
        {
            Regex r = new Regex("<img[\\s\\S]*?>"); //找到<img>
            Match m = r.Match(html);
            string temp = html;
            while (m.Success)
            {
                temp = temp.Replace(m.Value, "<center>" + m.Value + "</center>");
                m = m.NextMatch();
            }
            return temp;
        }
        public static string ToHtml(string md_str)
        {
            if (md_str == null)
                return new string("");

            string html = Markdig.Markdown.ToHtml(md_str);

            //增加标题锚点  
            html = InsertHoverLabel(html, "<h1>");
            html = InsertHoverLabel(html, "<h2>");
            html = InsertHoverLabel(html, "<h3>");
            html = InsertHoverLabel(html, "<h4>");
            html = InsertHoverLabel(html, "<h5>");
            html = InsertHoverLabel(html, "<h6>");

            //图片居中处理
            html = SetImageCenter(html);

            //处理数学公式
            var s = new string(ReplaceFlag(html));

            return s;
        }

        /// <summary>
        /// 将字符串文本进行网页输出（标签进行转义处理）
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string ToHtmlDecode(string str)
        {
            if (str == null)
                return new string("");
            var html = HttpUtility.HtmlDecode(str);
            html = html.Replace("\n", "<br/>");
            html = html.Replace(" ", "&nbsp;");
            html = html.Replace("\t", "&nbsp;&nbsp;&nbsp;&nbsp;");
            //处理数学公式
            var s = new string(html);

            return s;
        }


        /// <summary>
        /// 将markdown中的数学公式标记符$ ... $转换为mathjax可识别的\( ... \)符号
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string ReplaceFlag(string str)
        {
            if (string.IsNullOrWhiteSpace(str))
                return "";

            str = str.Replace("$$", "$"); //替换$$=>$
            // $..$  =>  \(  ... \)
            Regex r = new Regex("\\$(?<value>[\\s\\S]*?)\\$");
            Match m = r.Match(str);
            string temp = str;
            while (m.Success)
            {
                temp = temp.Replace(m.Value, "\\(" + m.Groups["value"] + "\\)");
                m = m.NextMatch();
            }
            return temp;
        }
    }
}